
import os
import re
import sqlite3

class Netlist2LOC:
    schNetName=[]
    LOCinFPGA=[]

    inputNetlistLines=[]

    originNetMap=[]
    searchResult=[]
    inputFilePath=''
    test_on = False
    searchPartFilter=''
    def __init__(self):
        pass
        # conn=sqlite3.connect('netlist.db')
        # cursor = conn.cursor()
        # cursor.execute('create table user (NetName varchar(20) primary key, LOC varchar(20))')
    def searchNet_fullName(self, netKeyWords, searchType):
        self.searchResult.clear()
        line_index=0
        for netLOCMap in self.originNetMap:
            if (bool)(re.search(netKeyWords, netLOCMap[searchType], re.IGNORECASE)):
            # if netKeyWords in  netLOCMap[0]:
                if self.searchPartFilter!='':
                    if (bool)(re.search(self.searchPartFilter, netLOCMap[1], re.IGNORECASE)):
                        line_index = line_index+1
                        print(str(line_index)+' : ',netLOCMap)
                        self.searchResult.append(netLOCMap)
                else:
                    line_index = line_index+1
                    print(str(line_index)+' : ',netLOCMap)
                    self.searchResult.append(netLOCMap)
        
    def writeMapFile(self):
        outfile=self.inputFilePath.replace('.csv','')+'.map'
        f=open(outfile, 'w', encoding='utf-8')
        f.write('line length='+str(len(self.originNetMap))+'\n')
        for item in self.originNetMap:
            f.write((item[0]+','+ item[1]))
        f.close()


    def genSignalLOCMap(self):

        # open & read input file list
        with open(self.inputFilePath, 'r', encoding='utf-8') as f:

            lines=f.readlines()
            if self.test_on:
                lineLength=100
            else:
                lineLength=len(lines)
            for i in range(1, lineLength):
                self.pcbNetlistFileFilter(lines[i])
        if self.test_on:
            self.showOriginNetMap()
            pass
    # for cadence PCB netlist file
    def pcbNetlistFileFilter(self, line):
        if '.' in line:
            line_arry=line.split(',')
            self.originNetMap.append( (line_arry[0], line_arry[1]) )
        # self.writeMapFile()

    def showOriginNetMap(self):
        for item in self.originNetMap:
            print(item)

    # work stream
    def askAndSearch(self):
    # after we get the net to loc map, we can search and select some lines to gen xdc
        print("""\nPlease input a Net Name to Search, or
        input * to view all Nets""")
        netKeyWords = input()
        # while (re.match('^[0-9a-zA-Z_]',netKeyWords)!=None):
        #     print("Please input a Net Name to Search :")
        #     netKeyWords = input()
        if '*'==netKeyWords:
            self.showOriginNetMap()
        else:
            print("\nSearch ",netKeyWords," :\n")
            

            
            self.searchNet_fullName(netKeyWords)
            print("\nPlease select lines to generate XDC ")
            self.genXDCFromSelectedLines()

    def clear(self):
        self.originNetMap.clear()
        self.searchResult.clear()
        
    def genXDCFromSelectedLines(self):
        pass





def main():
    netlist2LOC = Netlist2LOC() 
    funcNumStr=['1','2','q']
    while(True):

        if len(netlist2LOC.originNetMap)==0:
             print("""\nPlease select function:
    1: open a new Netlist file
    q: quit""")
        else:
            # function selection
            print("""\nPlease select function:
    1: open a new Netlist file
    2: search net name in current netlist
    q: quit""")
        funcSel=input()
        while(funcSel not in funcNumStr):
            print("""\nPlease select function:
    1: open a new Netlist file
    2: search net name in current netlist
    q: quit""")
            funcSel=input()
        
        if funcSel == '1':
            print("\nPlease input Netlist file Path(CSV):")
            
            netlist2LOC.inputFilePath=input()
            while(os.path.exists(netlist2LOC.inputFilePath)==False):
                print("\nPlease input a VALID Netlist file Path(CSV):")
                netlist2LOC.inputFilePath=input()

            
            netlist2LOC.genSignalLOCMap()
            netlist2LOC.askAndSearch()
        elif funcSel == '2':
            netlist2LOC.askAndSearch()
            
        elif funcSel == 'q':
            exit(0)



if __name__ == "__main__":
    main()
